﻿#coding:utf-8
import calendar
import codecs

from django.http import JsonResponse,HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import authentication_classes
import os
import pandas as pd
import xlwt
from io import BytesIO
from django.forms.models import model_to_dict
import datetime
import time
from OnlineJudge.utils import PublicMethods as pub
from django.db import connection  # django封装好的方法
from django.utils import timezone
import random
from OnlineJudge import models
from django.contrib.auth.hashers import make_password, check_password #引用djago自带的加密解密
from OnlineJudge.models import *
import redis as rs,time,json
from django.db.models import Q #导入Q查询
import re #正则分割字符串
import decimal
# Create your views here.
from OnlineJudge.models import *
from OnlineJudge.models import Solution as so
# from Online_Judge import images
from Online_Judge import settings
#from xml.dom.minidom import parse
#import xml.dom.minidom
import xml.etree.cElementTree as ET
#import xml.etree.ElementTree as ET  # 迭代生成xml
import xml.dom.minidom as MD  # 输出
from  xml.dom import  minidom
from datetime import datetime as dtime
from OnlineJudge.utils.PublicMethods import *   #导入公共方法
from django.core.cache import cache

#全局配置redis
redis = rs.Redis(password=config.REDISP_PASS)

'''
creator : yby
createTime: 2020.12.03
description:课程页面首页数据
status:开发
updateTime:2020.12.24
remask:传回listType字段，通过该变量判断传回的四个课程是什么类型的课程
'''
def courseIndex(request):
    listType = int(request.GET.get('listType','0'))
    if listType == 1:   #最热课程
        with connection.cursor() as cursor:
            cursor.execute("SELECT courses.course_id, courses.title, courses.`explain`, courses.type_id, courses.price, courses.photo_add, courses.evaluation_num, courses.view_num, courses.browse_num, courses.member_num FROM courses WHERE courses.defunct = 0 AND courses.`status` = 'published' ORDER BY courses.member_num DESC LIMIT 4")
            solution_data = cursor.fetchall()
        solution_data = list(solution_data)
    elif listType == 2: #推荐课程
        with connection.cursor() as cursor:
            cursor.execute("SELECT courses.course_id, courses.title, courses.`explain`, courses.type_id, courses.price, courses.photo_add, courses.evaluation_num, courses.view_num, courses.browse_num, courses.member_num FROM course_commend , courses WHERE course_commend.course_id = courses.course_id AND course_commend.defunct = 0 AND courses.defunct = 0 AND courses.`status` = 'published' ORDER BY course_commend.display_num ASC LIMIT 4 ")
            solution_data = cursor.fetchall()
        solution_data = list(solution_data)
    else:   #否则最新
        with connection.cursor() as cursor:
            cursor.execute("SELECT courses.course_id, courses.title, courses.`explain`, courses.type_id, courses.price, courses.photo_add, courses.evaluation_num, courses.view_num, courses.browse_num, courses.member_num FROM courses WHERE courses.defunct = 0 AND courses.`status` = 'published' ORDER BY courses.create_time DESC LIMIT 4")
            solution_data = cursor.fetchall()
        solution_data = list(solution_data)

    ans_data = []
    for data in solution_data:
        ans_data.append({
            'course_id':data[0],
            'title':data[1],
            'explain':data[2],
            'type_id':data[3],
            'price':data[4],
            'photo_add':data[5],
            'evaluation_num':data[6],
            'view_num':data[7],
            'browse_num':data[8],
            'member_num':data[9]
        })
    result = {"data":ans_data}
    return JsonResponse(result,safe=False)


# 获取个人信息
def getpersonData(request):
    if request.method == 'GET':
        userid = request.GET.get('userid')
    if len(userid) == 0:
        massage = {"err": "Please log in and try again."}
        return JsonResponse(massage)
    user_data = Users.objects.filter(user_id=userid).first()
    if user_data == None:
        massage = {'err': 'None'}
        return JsonResponse(massage, safe=False)
    gender = {"M": "男", "N": "未知", "F": "女"}
    pass1 = {"N": "未验证", "Y": "已验证"}
    massage = {
        "realname": user_data.real_name,
        "userid": user_data.user_id,
        "nick": user_data.nick,
        "email": user_data.email,
        "regtime": user_data.reg_time,
        "sex": gender[user_data.sex],
        "school": user_data.school,
        "score": user_data.score,
        "judgepassword": "已设置",
        "judgeemail": pass1[user_data.email_act],
    }
    return JsonResponse(massage, safe=False)


# 课程模糊查找
def courseSearch(request):
    if request.method == 'GET':
        coursedata = request.GET.get('coursedata')
        page = int(request.GET.get('page'))
    coursedata = coursedata.replace(" ", "")
    data = Courses.objects.filter(title__icontains=coursedata, defunct=0)
    data = data.order_by('-view_num')
    total = len(data)
    massage = []
    pan = ["免费", "收费"]
    status = {"published": "已发布", "unpublished": "未发布", "create": "创建"}
    data = data[(page - 1) * 24:page * 24]
    num = (page - 1) * 24
    for data1 in data:
        h = 1
        if data1.price == 0:
            h = 0
        num += 1
        massage1 = {
            'number': num,
            'coursename': data1.title,
            'explain': data1.explain,
            'type_id': data1.type_id,
            'price': data1.price,
            'photo': data1.photo_add,
            'createtime': data1.create_time,
            'createuser': data1.creator,
            'viewnum': data1.view_num,
            'evaluationnum': data1.evaluation_num,
            'charges': pan[h],
            'status': status[data1.status],
        }
        massage.append(massage1)
    return JsonResponse({'massage': massage, 'total': total}, safe=False)


# 添加课程
def addCurriculum(request):
    if request.method == 'GET':
        title = request.GET.get('title')
        explain = request.GET.get('explain')
        type_id = request.GET.get('type_id')
        price = request.GET.get('price')
        photo_add = request.GET.get('photo')
        creator = request.GET.get('creator')
        status = request.GET.get('status')
    statusdata = ['published', 'unpublished', 'create']
    if status not in statusdata:
        massage = {'err': 'Wrong status.'}
        return JsonResponse(massage, safe=False)
    if type_id.isdigit() == False:
        massage = {'err': 'Wrong typeid.'}
        return JsonResponse(massage, safe=False)
    type_id = int(type_id)
    typedata = CourseType.objects.filter(type_id=type_id)
    if len(typedata) == 0:
        massage = {'err': 'This course type does not exist.'}
        return JsonResponse(massage, safe=False)
    if price.count('.') > 1:
        massage = {'err': 'Wrong price.'}
        return JsonResponse(massage, safe=False)
    else:
        if (price.replace('.', '')).isdigit() == False:
            massage = {'err': 'Wrong price.'}
            return JsonResponse(massage, safe=False)
    if len(title) == 0 or len(title) > 36:
        massage = {'err': 'Course name length greater than 0 cannot exceed 36.'}
        return JsonResponse(massage, safe=False)
    if len(price) == 0:
        price = '0'
    price = round(float(price), 2)
    if len(photo_add) == 0 or len(creator) == 0:
        massage = {'err': 'Please complete the information.'}
        return JsonResponse(massage, safe=False)
    time = timezone.now()
    save_course = Courses(title=title, explain=explain, type_id=type_id, price=price, photo_add=photo_add,
                          evaluation_num=0,
                          view_num=0, browse_num=0, member_num=0, create_time=time, creator=creator, defunct=0,
                          status=status
                          )
    save_course.save()
    massage = {'err': 'Added successfully.'}
    return JsonResponse(massage, safe=False)


# 显示课程
def showCourses(request):
    if request.method == 'GET':
        page = int(request.GET.get('page'))
    courses = Courses.objects.filter(defunct=0).order_by('-view_num')
    total = len(courses)
    data = courses[(page - 1) * 24:page * 24]
    num = (page - 1) * 24
    massage = []
    pan = ["免费", "收费"]
    status = {"published": "已发布", "unpublished": "未发布", "create": "创建"}
    for data1 in data:
        num += 1
        h = 1
        if data1.price == 0:
            h = 0
        massage1 = {
            'number': num,
            'coursename': data1.title,
            'explain': data1.explain,
            'type_id': data1.type_id,
            'price': data1.price,
            'photo': data1.photo_add,
            'createtime': data1.create_time,
            'createuser': data1.creator,
            'viewnum': data1.view_num,
            'evaluationnum': data1.evaluation_num,
            'charges': pan[h],
            'status': status[data1.status],
        }
        massage.append(massage1)
    return JsonResponse({'massage': massage, 'total': total}, safe=False)


# 我的正在进行的课程
def myCourse(request):
    if request.method == 'GET':
        userid = request.GET.get('userid')
        page = int(request.GET.get('page'))
    coursedata = CourseMember.objects.values('course_id').filter(user=userid)
    courses = Courses.objects.filter(defunct=0, course_id__in=coursedata)
    total = len(courses)
    data = courses[(page - 1) * 24:page * 24]
    num = (page - 1) * 24
    massage = []
    pan = ["免费", "收费"]
    status = {"published": "已发布", "unpublished": "未发布", "create": "创建"}
    for data1 in data:
        num += 1
        h = 1
        if data1.price == 0:
            h = 0
        massage1 = {
            'number': num,
            'coursename': data1.title,
            'explain': data1.explain,
            'type_id': data1.type_id,
            'price': data1.price,
            'photo': data1.photo_add,
            'createtime': data1.create_time,
            'createuser': data1.creator,
            'viewnum': data1.view_num,
            'evaluationnum': data1.evaluation_num,
            'charges': pan[h],
            'status': status[data1.status],
        }
        massage.append(massage1)
    return JsonResponse({'massage': massage, 'total': total}, safe=False)


# 我的已结束课程
def myClosingsession(request):
    if request.method == 'GET':
        userid = request.GET.get('userid')
        page = int(request.GET.get('page'))
    coursedata = CourseMember.objects.values('course_id').filter(user=userid)
    courses = Courses.objects.filter(defunct=1, course_id__in=coursedata)
    total = len(courses)
    data = courses[(page - 1) * 24:page * 24]
    num = (page - 1) * 24
    massage = []
    pan = ["免费", "收费"]
    status = {"published": "已发布", "unpublished": "未发布", "create": "创建"}
    for data1 in data:
        num += 1
        h = 1
        if data1.price == 0:
            h = 0
        massage1 = {
            'number': num,
            'coursename': data1.title,
            'explain': data1.explain,
            'type_id': data1.type_id,
            'price': data1.price,
            'photo': data1.photo_add,
            'createtime': data1.create_time,
            'createuser': data1.creator,
            'viewnum': data1.view_num,
            'evaluationnum': data1.evaluation_num,
            'charges': pan[h],
            'status': status[data1.status],
        }
        massage.append(massage1)
    return JsonResponse({'massage': massage, 'total': total}, safe=False)



